'use strict';

module.exports = app => {
  const { router, controller } = app;

  // 认证相关路由
  router.post('/api/auth/register', controller.auth.register);
  router.post('/api/auth/login', controller.auth.login);
  router.post('/api/auth/logout', controller.auth.logout);
  router.get('/api/auth/userinfo', controller.auth.getUserInfo);
  
  // 用户管理路由（需要登录）
  router.put('/api/auth/profile', app.middleware.auth(), controller.auth.updateProfile);
  router.put('/api/auth/password', app.middleware.auth(), controller.auth.changePassword);
  router.get('/api/auth/stats', app.middleware.auth(), controller.auth.getUserStats);

  // 房源浏览路由
  router.get('/api/properties', controller.properties.list);
  router.get('/api/properties/:id', controller.properties.detail);

  // 房源评价路由
  router.get('/api/properties/:propertyId/reviews', controller.reviews.list);
  router.get('/api/properties/:propertyId/reviews/stats', controller.reviews.stats);
  router.post('/api/reviews', app.middleware.auth(), controller.reviews.create);
  router.put('/api/reviews/:id/status', app.middleware.auth(), controller.reviews.updateStatus);

  // 房源管理路由（需要登录）
  router.post('/api/properties', app.middleware.auth(), controller.properties.create);
  router.put('/api/properties/:id', app.middleware.auth(), controller.properties.update);
  router.delete('/api/properties/:id', app.middleware.auth(), controller.properties.delete);
  router.get('/api/user/properties', app.middleware.auth(), controller.properties.getUserProperties);

  // 预约看房路由
  router.post('/api/appointments', app.middleware.auth(), controller.appointments.create);
  router.get('/api/appointments', app.middleware.auth(), controller.appointments.getUserAppointments);
  router.get('/api/appointments/:id', app.middleware.auth(), controller.appointments.detail);
  router.put('/api/appointments/:id/status', app.middleware.auth(), controller.appointments.updateStatus);
  router.put('/api/appointments/:id/cancel', app.middleware.auth(), controller.appointments.cancel);
  router.get('/api/properties/:propertyId/appointments', app.middleware.auth(), controller.appointments.getPropertyAppointments);

  // 健康检查
  router.get('/', async ctx => {
    ctx.body = {
      success: true,
      message: '房地产平台后端服务运行正常',
      timestamp: new Date(),
    };
  });

  // 用户管理路由
  router.get('/api/users', async ctx => {
    try {
      const users = await ctx.service.user.findAll();
      ctx.body = {
        success: true,
        data: users,
      };
    } catch (error) {
      ctx.status = 500;
      ctx.body = {
        success: false,
        message: '获取用户列表失败',
      };
    }
  });
};